package com.dx.oa.framework.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.dx.oa.framework.dto.TreeDto;
import com.dx.oa.sysmng.entity.Menu;

/**
 * 关于树形结构的工具类
 * @author dx911
 *
 */
public class TreeUtil {
	
	private static Map<Integer,List<TreeDto>> child;
	private static Set<Integer> mset;
	public static void dfs(Integer parentId,TreeDto nowmenu,List<TreeDto> sortMenuList)
	{
		if(nowmenu != null)
			sortMenuList.add(nowmenu);
		List<TreeDto> nowlist = child.get(parentId);
		if(nowlist == null)
			return;
		for (int i = 0; i < nowlist.size(); i++) {
			TreeDto tmenu = nowlist.get(i);
			dfs(tmenu.getId(), tmenu, sortMenuList);
		}
	}
	

	public static void init(List<TreeDto> menuList)
	{
		child = new HashMap<Integer,List<TreeDto>>();
		Collections.sort(menuList);
		for(int i=0; i<menuList.size(); i++)
		{
			TreeDto nowMenu = menuList.get(i);
			Integer pid = nowMenu.getParentId();
			List<TreeDto> newlist = child.get(pid);
			if(newlist == null)
				newlist = new ArrayList<TreeDto>();
			newlist.add(nowMenu);
			child.put(pid, newlist);
		}
	}

	/**
	 * 使用泛型获取菜单列表
	 * @param menuList
	 * @param sortMenuList
	 * @param parentId
	 */
	public static<T> void sortTreeList(List<T> menuList,List<T> sortMenuList,Integer parentId)
	{
		init((List<TreeDto>)menuList);
		dfs(parentId, null, (List<TreeDto>)sortMenuList);
	}
	
	public static void markChildSet(Integer menuId)
	{
		mset.add(menuId);
		List<TreeDto> nowlist = child.get(menuId);
		if(nowlist == null)
			return;
		for (int i = 0; i < nowlist.size(); i++) {
			markChildSet(nowlist.get(i).getId());
		}
	}
	public static Set<Integer> getChildHashSet(List<TreeDto> menuList,Integer menuId) {
		// TODO Auto-generated method stub
		mset = new HashSet<Integer>();
		init(menuList);
		markChildSet(menuId);
		return mset;
		
	}
}
